import { NextRequest, NextResponse } from 'next/server';
import Database from 'better-sqlite3';
import path from 'path';

const DB_PATH = path.join(process.cwd(), 'data', 'delivery-management.db');

interface InstancePBSMapping {
  id: number;
  instance_id: string;
  pbs_level_id: number;
  pbs_instance_id: string;
  created_at: string;
}

// 生成实例PBS层级ID的函数
function generateInstancePBSId(instanceId: string, pbsLevelId: number): string {
  const timestamp = Date.now();
  const random = Math.random().toString(36).substring(2, 8);
  return `${instanceId}-PBS-${pbsLevelId}-${timestamp}-${random}`;
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { instanceId, pbsLevelId } = body;

    if (!instanceId || !pbsLevelId) {
      return NextResponse.json(
        { success: false, error: '缺少必需参数：instanceId 和 pbsLevelId' },
        { status: 400 }
      );
    }

    const db = new Database(DB_PATH);

    try {
      // 检查PBS层级是否存在
      const pbsCheckStmt = db.prepare('SELECT id, full_path FROM pbs_levels WHERE id = ?');
      const pbsLevel = pbsCheckStmt.get(pbsLevelId);
      
      if (!pbsLevel) {
        return NextResponse.json(
          { success: false, error: `PBS层级 ${pbsLevelId} 不存在` },
          { status: 404 }
        );
      }

      // 检查是否已经分配过
      const existingStmt = db.prepare(`
        SELECT pbs_instance_id FROM instance_pbs_mapping 
        WHERE instance_id = ? AND pbs_level_id = ?
      `);
      const existing = existingStmt.get(instanceId, pbsLevelId) as { pbs_instance_id: string } | undefined;
      
      if (existing) {
        // 如果已经分配过，返回现有的PBS实例ID
        return NextResponse.json({
          success: true,
          data: {
            pbsInstanceId: existing.pbs_instance_id,
            message: '返回现有的PBS层级分配',
            pbsLevel: pbsLevel
          }
        });
      }

      // 生成新的PBS实例ID
      const pbsInstanceId = generateInstancePBSId(instanceId, pbsLevelId);
      
      const insertStmt = db.prepare(`
        INSERT INTO instance_pbs_mapping (instance_id, pbs_level_id, pbs_instance_id)
        VALUES (?, ?, ?)
      `);
      
      const result = insertStmt.run(instanceId, pbsLevelId, pbsInstanceId);
      
      return NextResponse.json({
        success: true,
        data: {
          id: result.lastInsertRowid,
          pbsInstanceId,
          message: 'PBS层级分配成功',
          pbsLevel: pbsLevel
        }
      });

    } finally {
      db.close();
    }

  } catch (error) {
    console.error('分配PBS层级失败:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: '分配PBS层级失败',
        details: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    );
  }
}

// 获取实例的PBS映射
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const instanceId = searchParams.get('instanceId');

    if (!instanceId) {
      return NextResponse.json(
        { success: false, error: '缺少参数：instanceId' },
        { status: 400 }
      );
    }

    const db = new Database(DB_PATH);

    try {
      const stmt = db.prepare(`
        SELECT 
          ipm.*,
          pl.level1_area,
          pl.level2_category,
          pl.level3_subitem,
          pl.full_path,
          pl.pbs_code
        FROM instance_pbs_mapping ipm
        JOIN pbs_levels pl ON ipm.pbs_level_id = pl.id
        WHERE ipm.instance_id = ?
        ORDER BY ipm.created_at DESC
      `);
      
      const mappings = stmt.all(instanceId);
      
      return NextResponse.json({
        success: true,
        data: mappings,
        message: `找到 ${mappings.length} 条PBS映射记录`
      });

    } finally {
      db.close();
    }

  } catch (error) {
    console.error('获取PBS映射失败:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: '获取PBS映射失败',
        details: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    );
  }
}

// 删除PBS层级分配
export async function DELETE(request: NextRequest) {
  try {
    const body = await request.json();
    const { instanceId, pbsLevelId, pbsInstanceId } = body;

    if (!instanceId || (!pbsLevelId && !pbsInstanceId)) {
      return NextResponse.json(
        { success: false, error: '缺少必需参数' },
        { status: 400 }
      );
    }

    const db = new Database(DB_PATH);

    try {
      let deleteStmt;
      let params: any[];

      if (pbsInstanceId) {
        // 按PBS实例ID删除
        deleteStmt = db.prepare(`
          DELETE FROM instance_pbs_mapping 
          WHERE instance_id = ? AND pbs_instance_id = ?
        `);
        params = [instanceId, pbsInstanceId];
      } else {
        // 按层级ID删除
        deleteStmt = db.prepare(`
          DELETE FROM instance_pbs_mapping 
          WHERE instance_id = ? AND pbs_level_id = ?
        `);
        params = [instanceId, pbsLevelId];
      }

      const result = deleteStmt.run(...params);

      if (result.changes === 0) {
        return NextResponse.json(
          { success: false, error: '未找到要删除的PBS映射记录' },
          { status: 404 }
        );
      }

      return NextResponse.json({
        success: true,
        message: 'PBS层级分配删除成功',
        data: { deletedCount: result.changes }
      });

    } finally {
      db.close();
    }

  } catch (error) {
    console.error('删除PBS层级分配失败:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: '删除PBS层级分配失败',
        details: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    );
  }
}